package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcWorkTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcWorkTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  private static final Map<L1NpcInstance, Integer> _map = new HashMap<>();
  
  public static void put(L1NpcInstance npc, Integer time) {
    _map.put(npc, time);
  }
  
  public void start() {
    int timeMillis = 2000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 2000L, 2000L);
  }
  
  public void run() {
    try {
      if (_map.isEmpty())
        return; 
      Iterator<L1NpcInstance> iterator = _map.keySet().iterator();
      while (iterator.hasNext()) {
        L1NpcInstance npc = iterator.next();
        Integer time = _map.get(npc);
        time = Integer.valueOf(time.intValue() - 2);
        if (time.intValue() > 0) {
          _map.put(npc, time);
        } else {
          startWork(npc);
        } 
        Thread.sleep(50L);
      } 
    } catch (Exception e) {
      _log.error("NPC工作时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcWorkTimer workTimer = new NpcWorkTimer();
      workTimer.start();
    } 
  }
  
  private static void startWork(L1NpcInstance npc) {
    try {
      if (npc != null) {
        int time = npc.WORK.workTime();
        if (time != 0) {
          npc.WORK.work(npc);
          _map.put(npc, Integer.valueOf(time));
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
